#Get objects
old_ws = ls()

######################
#Read in descriptives#
######################

files = './output/descriptives' %>% list.files() 

table_parts = list()

for (f in files) {
  temp = fread(paste0('./output/descriptives/',f))
  temp[, group := str_replace(f, "\\.csv$", "")]
  table_parts[[str_replace(f, "\\.csv$", "")]] = temp
}

########################
#Descriptives: Table C2#
########################

dv_table = table_parts[c('nvms', 'podes', 'security', 'ifls')] %>%
  rbindlist %>%
  .[,-7] %>%
  .[1:20]

dv_table$Variable = c(
  paste("NVMS Type", 1, "Count"),
  paste("NVMS Type", 1, "Deaths"),
  paste("NVMS Type", 1, "(Binary)"),
  paste("NVMS Type", 1, "Deaths (Binary)"),
  paste("PODES Type", 1, "Count"),
  paste("PODES Type", 1, "Deaths"),
  paste("PODES Type", 1, "(Binary)"),
  paste("PODES Type", 1, "Deaths (Binary)"),
  '% Villages add security guard',
  '% Villages add security post',
  '% villages add civil defense force',
  'Security index',
  'Intolerance: other religion live in village',
  'Intolerance: other religion is neighbor',
  'Intolerance: other religion rents room',
  'Intolerance: other religion marries child',
  'Intolerance: other religion building',
  'Intolerance: mean of 5 item',
  '% most intolerant on all measures',
  '% most intolerant on any measures'
)

dv_table = dv_table[c(1,3,2,4,5:18),] 
dv_table[, Variable := str_replace(Variable, "Type 1 ", "")]
dv_table %>%
  stargazer(type = 'latex', summary = F, 
            title = "Descriptive Statistics (Dependent Variables)",
            label = 'tab:desc_main', rownames = F,
            out = './output/tables/table_c2.tex',
            style = 'apsr')



########################
#Descriptives: Table D1#
########################
table_parts[c('balance_first_round', 'balance_election_att', 'balance_dapil_att', 'balance_dapil_frac')] %>% 
  rbindlist %>%
  .[,-7] %>%
  stargazer(type = 'latex', summary = F, 
            title = "Descriptive Statistics (Balance Outcomes)",
            label = 'tab:desc_balance', rownames = F,
            out = './output/tables/table_d1.tex',
            style = 'apsr')

#Clean up
drop = setdiff(ls(), c(old_ws)) 
rm(list = drop)